use prost::{self, Message};

mod pb;
use pb::{PbDeviceInfo, PbNetInfo, PbServerInfo, PbTerninalConfigration};

fn main() {
    let mut config = PbTerninalConfigration {
        /* 成员字段赋值使用Some枚举 */
        device_info: Some(PbDeviceInfo {
            terminal_sn: String::from("123456"),
        }),
        net_info: Some(PbNetInfo {
            mac_addr: vec![0xff, 0x01, 0x02, 0x03],
            use_dhcp: true,
            ip: u32::from_be_bytes([192, 168, 1, 2]),
            gateway: u32::from_be_bytes([192, 168, 1, 1]),
            subnet_mask: u32::from_be_bytes([255, 255, 255, 255]),
            dns: u32::from_be_bytes([8, 8, 8, 8]),
        }),
        server_info: Some(PbServerInfo {
            hostname: String::from("www.baidu.com"),
            port: 8080 as u32, // u16变成了u32
        }),
    };
    // 对单个结构体类型成员的赋值操作，和c++,python一样都是copyfrom
    config.device_info.clone_from(&Some(PbDeviceInfo {
        terminal_sn: String::from("123456"),
    }));

    // 打印原始数据
    println!("原始数据：");
    println!("{:?}\n", config);

    // 序列化
    let mut bytes = Vec::new();
    config.encode(&mut bytes).unwrap();
    println!("序列化后的数据：");
    println!("{:?}\n", bytes);

    // 反序列化
    let unmarshal_config = PbTerninalConfigration::decode(&bytes[..]).unwrap();
    println!("反序列化后的数据：");
    println!("{:?}\n", unmarshal_config);

    assert_eq!(config, unmarshal_config, "序列化前后不相同！");
}
